#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <linux/if.h>
#include <linux/if_tun.h>
#include <assert.h>

#include "defs.h"
#include "tools.h"

void * keep_live(void * arg)
{
    printf("Start keep_live ...\n");
    struct Msg msg;
    int heartb_len = 5;
    memset(&msg, 0, MSGLENGTH);
    msg.length = htonl(heartb_len);
    msg.type = 104;
    p_buf(&msg, 8, MSGLENGTH);
    while (1)
    {
        sleep(1);
        //printf("++++ heartbeat ++++\n");
        time_t cur = time(NULL);
        uinfoptr le = utable_he;
        for (; le != NULL; le = le->pNext)
        {
            if (--le->count <= 0)
            {
                // 20s发送一次心跳包
                le->count = 20;
                write_all(le->fd, &msg, heartb_len);
                p_time_prompt("ASK");
                printf("require heartbeat %d\n", le->fd);
            }
            if (cur - le->secs > 60)
            {
                // 超时，删除链接
                p_time_prompt("TIMEOUT");
                printf("%d\n", le->fd);
                if (remove_client(le))
                {
                    perror("remove client");
                    exit(errno);
                }
            }
        }
    }
}
